// components/header/header.js
const app = getApp();
import { stopGlobalTimer } from '../../utils/timer';
import answerUtil from "../../utils/answerUtil";
import ajax from "../../utils/ajax";
Component({
  data: {
    navBarHeight: 0,
    menuRight: app.globalData.menuRight,
    menuBottom: 0,
    menuHeight: app.globalData.menuHeight,
    total: 0, //题目总数
    number: 0, //当前题目数
    percent: 0, //题目进度
    time: app.globalData.elapsed, //时间
    minutes: 40, //分钟
    submitState:false,//提交状态
  },
  attached() {
    const set =new Set()
    let answerRecords = wx.getStorageSync('answerRecords') || [];
    answerRecords.forEach(element => {
      set.add(element.classify)
    });
    let number = set.size + 1;

    const questionList = wx.getStorageSync('questionInfo').questionList;
    let total = questionList.length;
    if(number > total){
      number = total
    }
    this.setData({
      total,
      menuBottom: Math.round(app.globalData.menuBottom) // 四舍五入取整
    });
    this.stopTimer();

    // 如果没有开始时间，则设置开始时间为现在
    let startTime = wx.getStorageSync('startTime');
    if (!startTime) {
      startTime = Date.now();
      wx.setStorageSync('startTime', startTime);
    }
    // 立即更新时间显示
    this.updateTimeDisplay();
    // 每半秒更新一次 UI 时间
    this.globalDataUpdateInterval = setInterval(() => {
      this.updateTimeDisplay();
      // 40分钟倒计时结束还未完成，提交试卷
      if (this.data.minutes <= 0) {
        this.endTest();
      }
    }, 500);

    this.percent(number);
    if (app.globalData.isIOS) {
      this.setData({
        navBarHeight:48
      })
    } else {
      this.setData({
        navBarHeight:app.globalData.navBarHeight,
      })
    }
  },

  // 清除定时器
  detached(){
    if (this.globalDataUpdateInterval) {
      clearInterval(this.globalDataUpdateInterval);
    }
    // this.stopTimer();
  },
  methods: {
    // 时间更新方法
    // updateTimeDisplay() {
    //   const elapsed = wx.getStorageSync('elapsed');
    //   const minutes = Math.ceil(elapsed / 60);
    //   this.setData({
    //     time: elapsed,
    //     minutes,
    //   });
    // },
     // 时间更新方法
     updateTimeDisplay() {
      // 获取开始时间
      const startTime = wx.getStorageSync('startTime');
      if (!startTime) return;
      
      // 计算已用时间（秒）
      const currentTime = Date.now();
      const elapsed = Math.floor((currentTime - startTime) / 1000);
      
      // 计算剩余分钟数
      const remainingTime = 40 * 60 - elapsed; // 40分钟总时间
      const minutes = Math.max(0, Math.ceil(remainingTime / 60));
      
      this.setData({
        time: elapsed,
        minutes,
      }); 
    },
    // 答题进度
    percent(number) {
      const {total} = this.data;
      let percent = Math.floor((number / total) * 100);
      this.setData({
        number,
        percent
      });
    },

    // 停止计时器
    stopTimer() {
      if (this.globalDataUpdateInterval) {
        clearInterval(this.globalDataUpdateInterval);
        this.globalDataUpdateInterval = null; // 清空引用
      }
    },
    // 结束答题
    endTest(){
      let submitState = this.data.submitState;
      if(submitState){
        return
      }
      this.setData({
        submitState:true
      })
      this.stopTimer();// 停止计时器
      stopGlobalTimer(); // 停止全局计时器
      wx.showToast({
        title: '已超时，提交试卷',
        icon: 'none',
        duration: 1000
      });
      
      setTimeout(()=>{
        const savedAnswerRecords = answerUtil.getAnswerRecords();
        const answerBaseData = wx.getStorageSync('answerBaseArray');
        // 添加answerBaseArray中的数据到答题数组中
        const totalRecords = savedAnswerRecords.map(item => {
          return {
            ...item,
            ...answerBaseData
          };
        });
        
        // 提交答题信息
        ajax.postMethod('business/app/anwsers/wx/saveBatch', totalRecords).then(res => {
          console.log('提交答题信息',res)
          if(res.code !== 200){
            wx.showToast({
              title: res.msg,
              icon:'none'
            })
          }
        }).catch(err => {
          console.error('答题信息提交失败', err);
        });
        wx.reLaunch({
          url: '../../pages/topic-another/topic-another',
        })
      },1000)
    }
  }
});